﻿using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Todo.Helpers;
using Todo.Models;

namespace Todo
{
    public partial class Login : Form
    {
        private readonly HttpClient client;
        public Login()
        {
            InitializeComponent();
            client = HttpClientHelper.CreateHttpClient(string.Empty);
        }

        private async void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                var jsonStr = JsonSerializer.Serialize(new
                {
                    UserName = txtAccount.Text,
                    Password = txtPassword.Text
                });
                var content = new StringContent(jsonStr, Encoding.UTF8, "text/json");
                var result = await client.PostAsync("/Login", content);
                result.EnsureSuccessStatusCode();
                var objResult = await result.Content.ReadFromJsonAsync<ResponseModelResult<ResponseLogin>>();
                if (objResult!.Code != 200)
                {
                    MessageBox.Show(objResult.Msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var responseLogin = objResult!.Data;
                LoginInfo.CurrentUser = responseLogin;
                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }
}
